Passed
Push — master ( 01829a...af608e )
by Dev
03:30
created

helpers.js ➔ responsiveImage   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 17
rs 9.2833
c 1
b 0
f 0
cc 5
nc 5
nop 1
1
/**
2
 * List of available function:
3
 * - formToSky              ajaxify-form
4
 * - getBlockFromSky        Fetch (ajax) function permitting to get block via a POST request
5
 * - responsiveImage        Transform image's path (src) produce with Liip to responsive path
6
 * - convertImgLinkToResponsiveImgLink      Transform link to image produce with Liip to responsive Link
7
*/
8
9
10
/**
11
 * Fetch (ajax) function permitting to get block via a POST request
12
 * (prevent from spam)
13
 *
14
 * @param {string} attribute
15
 */
16
export function getBlockFromSky(attribute = 'data-sky') {
17
    document.querySelectorAll('['+attribute+']').forEach(item => {
18
        fetch(item.getAttribute(attribute), {
19
          headers: {"Content-Type": "application/json", "Accept": "text/plain"},
20
          method: "POST",
21
          // Later: maybe implement sending data form data-post
22
          // body: JSON.stringify({"contact": (document.getElementById("contact") !== null ? 1: 0)}),
23
          credentials: "same-origin"
24
        }).then(function(response) {
25
          return response.text()
26
        }).then(function(body) {
27
            item.removeAttribute('data-sky');
28
            item.innerHTML = body;
29
30
            // add export function to reDo on document dom ready
31
            if (typeof onPageLoaded === 'function') onPageLoaded();
0 ignored issues
show
Bug introduced by
The variable onPageLoaded seems to be never declared. If this is a global, consider adding a /** global: onPageLoaded */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
32
            if (typeof onDomLoaded === 'function')  onDomLoaded();
0 ignored issues
show
Bug introduced by
The variable onDomLoaded seems to be never declared. If this is a global, consider adding a /** global: onDomLoaded */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
33
        });
34
    });
35
}
36
37
38
/**
39
 * ajaxify-form
40
 */
41
export function formToSky(userOptions = {}) {
42
43
44
    var options = {
45
        selector: '.ajax-form', // selector for ajax form
46
    };
47
    for (var attrname in userOptions) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
48
        options[attrname] = userOptions[attrname];
49
    }
50
51
  document.querySelectorAll(options.selector).forEach(item => {
52
      if (item.querySelector('form') !== null) {
53
          item.querySelector('form').addEventListener("submit", e => {
54
            e.preventDefault();
55
            sendFormToSky(e);
56
          });
57
       }
58
    });
59
60
    var sendFormToSky = function(form) {
61
        var $submitButton = getSubmitButton(form);
62
        if ($submitButton !== null) {
63
            var initialButton = getSubmitButton(form).outerHTML;
0 ignored issues
show
Unused Code introduced by
The variable initialButton seems to be never used. Consider removing it.
Loading history...
64
            $submitButton.outerHTML = '<i class="fa fa-spinner fa-spin"></i>';
65
        }
66
67
          //var formData = new FormData();
68
          var toSend = '';
69
          for (var i = 0; i < form.srcElement.length; ++i) {
70
                toSend += encodeURI(form.srcElement[i].name)+"="+encodeURI(form.srcElement[i].value)+'&';
71
          }
72
73
        var xmlhttp = new XMLHttpRequest();
74
        xmlhttp.addEventListener("load", function() {
75
            form.srcElement.outerHTML = xmlhttp.responseText;
76
            formToSky();
77
        }, false);
78
        xmlhttp.open("POST",form.srcElement.action,false);
79
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
80
        xmlhttp.send(toSend);
81
    }
82
83
    var renderError = function(error) {
0 ignored issues
show
Unused Code introduced by
The variable renderError seems to be never used. Consider removing it.
Loading history...
84
        var msg = '';
85
        for (var key in error) {
86
           if (error.hasOwnProperty(key)) {
87
              var obj = error[key];
88
              for (var prop in obj) {
89
                 if (obj.hasOwnProperty(prop)) {
90
                     msg += key + " : " + obj[prop] + '<br>';
91
                 }
92
              }
93
           }
94
        }
95
        return msg;
96
    }
97
98
    var getSubmitButton = function(form) {
99
        if (form.srcElement.querySelector('[type=submit]') !== null) {
100
            return form.srcElement.querySelector('[type=submit]');
101
        }
102
        if (form.srcElement.getElementsByTagName('button') !== null) {
103
            return form.srcElement.getElementsByTagName('button');
104
        }
105
        return null;
106
    }
107
}
108
109
/**
110
 * Transform image's path (src) produce with Liip to responsive path
111
 *
112
 * @param {string} src
113
 */
114
export function responsiveImage(src) {
115
  var screenWidth = document.clientWidth;
116
  if (screenWidth <= 576) {
117
    src = src.replace("/default/", "/xs/");
118
  } else if (screenWidth <= 768) {
119
    bg_src = src.replace("/default/", "/sm/");
0 ignored issues
show
Bug introduced by
The variable bg_src seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.bg_src.
Loading history...
120
  } else if (screenWidth <= 992) {
121
    bg_src = src.replace("/default/", "/md/");
122
  } else if (screenWidth <= 1200) {
123
    src = src.replace("/default/", "/lg/");
124
  } else {
125
    // 1200+
126
    src = src.replace("/default/", "/xl/");
127
  }
128
129
  return src;
130
}
131
132
133
/**
134
 * Transform link to image produce with Liip to responsive Link
135
 *
136
 * @param {string} attribute
137
 *
138
 * @example
139
 * <a href="/monImage/uneimage.png" data-rimg>
140
 * <a href="monimageopti.png">
141
 */
142
export function convertImgLinkToResponsiveImgLink(attribute = "data-rimg") {
143
  var test = [];
144
  if (typeof test.push === "function") {
145
    // to avoid gooogle bot execute
146
    [].forEach.call(document.querySelectorAll("[" + attribute + "]"), function(
147
      element
148
    ) {
149
      element.removeAttribute(attribute);
150
      var href = element.getAttribute(href);
0 ignored issues
show
Bug introduced by
The variable href seems to be never initialized.
Loading history...
151
      element.setAttribute('href', responsiveImage(href));
152
    });
153
  }
154
}
155